// 

import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage, useAccess, history, useModel } from '@umijs/max';
import { DataNode } from 'antd/es/tree';
import { Button, message, Modal, Dropdown, FormInstance, Space, Switch, Tag } from 'antd';
import { ActionType, FooterToolbar, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, DownOutlined } from '@ant-design/icons';
import UpdateForm from './components/routeForm';
import dayjs from 'dayjs';
import {getRouteList, removeRoute, addRoute, updateRoute, getPointsByRouteId} from '@/services/manage/route';

const { confirm } = Modal;

/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: API.Manage.Route) => {
  const hide = message.loading('正在添加');
  try {
    const resp = await addRoute({ ...fields });
    hide();
    if (resp.code === 200) {
      message.success('添加成功');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.Manage.Route) => {
  const hide = message.loading('正在更新');
  try {
    const resp = await updateRoute(fields);
    hide();
    if (resp.code === 200) {
      message.success('更新成功');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.Manage.Route[]) => {
  // console.log(selectedRows);  
  const hide = message.loading('正在删除');  
  if (!selectedRows) return true;
  try {
    const resp = await removeRoute(selectedRows.map((row) => row.routeId).filter((id): id is number => id !== undefined))
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const handleRemoveOne = async (selectedRow: API.Manage.Route) => {
  console.log(selectedRow);  
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    const params = [selectedRow.routeId];
    console.log(params)
    const resp = await removeRoute(params.filter((id): id is number => id !== undefined));
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 导出数据
 *
 *
 */
// const handleExport = async () => {
//   const hide = message.loading('正在导出');
//   try {
//     await exportRole();
//     hide();
//     message.success('导出成功');
//     return true;
//   } catch (error) {
//     hide();
//     message.error('导出失败，请重试');
//     return false;
//   }
// };


const routeTable: React.FC = () => {

  const [messageApi, contextHolder] = message.useMessage();
  const formTableRef = useRef<FormInstance>();

  const [modalVisible, setModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Manage.Route>();
  const [selectedRows, setSelectedRows] = useState<API.Manage.Route[]>([]);
  const [pageSize, setPageSize] = useState(10);
  const [routeTypes, setrouteTypes] = useState<string[]>([]);

  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser; 
  const routeIdRef = useRef<number>(); // 用于存储当前路线ID

  const access = useAccess();

  const [openModal, setOpenModal] = useState(false);
  const [currentRoute, setCurrentRoute] = useState<string>('');
  const [routePoints, setRoutePoints] = useState<string[]>([]);

  /** 国际化配置 */
  const intl = useIntl();
//   //获取故障类型
//   const routeTypes = async () => { 
//     const types = await getrouteNames()
//     console.log('types', types);   
//     const typeList = types?.rows
//     setrouteTypes(typeList)
//   }
  const taskStatusMap: Record<number, { color: string; text: string }> = {
    0: { color: 'gray', text: '未开始' },
    1: { color: 'blue', text: '进行中' },
    2: { color: 'green', text: '已完成' },
    3: { color: 'red', text: '中断' },
  };


  useEffect(() => {
    // routeTypes()
  }, []);


 const columns: ProColumns<API.Manage.Route>[] = [
 {
  title: '路线ID',
  dataIndex: 'routeId',
  align: 'center',
  hideInSearch: true,
  sorter: (a, b) => (a.routeId ?? 0) - (b.routeId ?? 0),
  defaultSortOrder: 'descend',  
  // render: (_, record) => (
  //   <a
  //     onClick={async () => {
  //       setCurrentRoute(record.routeId);
  //       const res = await getPointsByRouteId(record.routeId);
  //       const points = res.data?.map((point: API.Manage.Point) => point.pointId);     
  //       console.log('Route points:', points);       
  //       // const route = mockData.find((route) => route.routeName === record.routeName);
  //       setRoutePoints(points || []);
  //       setOpenModal(true);
  //     }}
  //     style={{ color: '#177DDC', cursor: 'pointer', textDecoration: 'underline' } }
  //   >
  //     {record.routeId}
  //   </a>
  // )
},
{
  title: '路线名称',
  dataIndex: 'routeName',
  align: 'center',
  valueType: 'text',
  render: (_, record) => (
    <a
      onClick={async () => {
        setCurrentRoute(record.routeName);
        const res = await getPointsByRouteId(record.routeId);
        const points = res.data?.map((point: API.Manage.Point) => point.pointId);     
        console.log('Route points:', points);       
        setRoutePoints(points || []);
        setOpenModal(true);
      }}
      style={{ color: '#177DDC', cursor: 'pointer', textDecoration: 'underline' } }
    >
      {record.routeName}
    </a>
  )
},
{
  title: '路线长度（米）',
  dataIndex: 'routeLength',
  align: 'center',
  valueType: 'digit',
  hideInSearch: true,
  render: (_, record) => record.routeLength?.toFixed(2) ?? '--',
},
{
  title: '预计耗时（分钟）',
  dataIndex: 'estimatedTime',
  align: 'center',
  valueType: 'digit',
  hideInSearch: true,
},
{
  title: '用户ID',
  dataIndex: 'userId',
  align: 'center',
  valueType: 'text',
  hideInSearch: true,
  ellipsis: true,
},
{
  title: '创建时间',
  dataIndex: 'createTime',
  align: 'center',
  valueType: 'dateTime',
  hideInSearch: true,
  sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
},
{
  title: '修改时间',
  dataIndex: 'updateTime',
  align: 'center',
  valueType: 'dateTime',
  sorter: (a, b) => new Date(a.updateTime).getTime() - new Date(b.updateTime).getTime(),
  hideInSearch: true,
},
{
  title: "操作" ,
  dataIndex: 'option',
  width: '220px',
  align: 'center',
  valueType: 'option',
  render: (_, record) => [
    // <Button
    //   type="link"
    //   size="small"
    //   style={{ color: '#3C9AE8' }}
    //   icon=<EditOutlined />
    //   hidden={!access.hasPerms('inspection:patrolRoute:edit')}
    //   onClick={() => {
    //     setCurrentRow(record);
    //     setModalVisible(true);
    //   }}
    // >
    //   编辑
    // </Button>,
    <Button
      type="link"
      size="small"
      danger
      key="delete"
      icon=<DeleteOutlined />
      hidden={!access.hasPerms('inspection:patrolRoute:remove')}
      onClick={async () => {
        Modal.confirm({
          title: '删除',
          content: '确定删除该路线吗？',
          okText: '确认',
          cancelText: '取消',
          onOk: async () => {
            const success = await handleRemoveOne(record);
            if (success) {
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          },
        });
      }}
    >
      删除
    </Button>,
  ],
},
];

  return (
    <PageContainer>
      {contextHolder}
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.Manage.Route>
          headerTitle='查询路线表格'
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="taskId"
          key="routeList"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('inspection:patrolRoute:add')}
              onClick={async () => {
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
            </Button>,
            <Button
              type="primary"
              key="remove"
              danger
              hidden={selectedRows?.length === 0 || !access.hasPerms('inspection:patrolRoute:remove')}
              onClick={async () => {
                Modal.confirm({
                  title: '是否确认删除所选数据项?',
                  icon: <ExclamationCircleOutlined />,
                  content: '请谨慎操作',
                  async onOk() {
                    const success = await handleRemove(selectedRows);
                    if (success) {
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.();
                    }
                  },
                  onCancel() { },
                });
              }}
            >
              <DeleteOutlined />
              <FormattedMessage id="pages.searchTable.delete" defaultMessage="删除" />
            </Button>,
            // <Button
            //   type="primary"
            //   key="export"
            //   hidden={!access.hasPerms('system:role:export')}
            //   onClick={async () => {
            //     handleExport();
            //   }}
            // >
            //   <PlusOutlined />
            //   <FormattedMessage id="pages.searchTable.export" defaultMessage="导出" />
            // </Button>,
          ]}
          request={(params) => {
            const { current, ...rest } = params;
            const queryParams = {
              pageNum: current,       // 将 current 映射为 pageNum
              pageSize: params.pageSize,
              ...rest,
            };            
            return getRouteList(queryParams as API.Manage.RouteListParams).then((res) => {
              const result = {
                data: res.rows,
                total: res.total,
                success: true,
              };
              return result;
            });
          }}
          
          columns={columns}
          columnsState={{
            persistenceKey: 'route-table',
            persistenceType: 'localStorage',
            defaultValue: {
              planStart: {show: false  }, // ✅ 默认隐藏，但用户可手动勾选
              planEnd: {show: false  },
              actualStart: {show: false  },
              actualEnd: {show: false  }
            },
          }}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
          pagination={{
            pageSize,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
              setPageSize(size);
            },
          }}
        />
      </div>
      {selectedRows?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />
              <a style={{ fontWeight: 600 }}>{selectedRows.length}</a>
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            key="remove"
            danger
            hidden={!access.hasPerms('inspection:patrolRoute:remove')}
            onClick={async () => {
              Modal.confirm({
                title: '删除',
                content: '确定删除该项吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  const success = await handleRemove(selectedRows);
                  if (success) {
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  }
                },
              });
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
        </FooterToolbar>
      )}
      <UpdateForm
        onSubmit={async (values) => {
          let success = false;    
          console.log('values:', values);   
          // success = await handleAdd({ ...values } as API.Manage.Route);      
          success = await handleUpdate({ ...values } as API.Manage.Route);
          // if (values.routeId) {
          //   console.log('UpdateForm values:', values);            
          //   success = await handleUpdate({ ...values } as API.Manage.Route);
          // } else {
          //   console.log('AddForm values:', values);            
          //   success = await handleAdd({ ...values } as API.Manage.Route);
          // }
          if (success) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        open={modalVisible}
        values={currentRow || {}}
      />
      <Modal
        open={openModal}
        title={`「${currentRoute}」的点位信息`}
        onCancel={() => setOpenModal(false)}
        footer={null}
      >
        {routePoints.length ? (
          <ul style={{ paddingLeft: 20 }}>
            {routePoints.map((point, index) => (
              <li key={index}>点位{point}</li>
            ))}
          </ul>
        ) : (
          <p>暂无点位数据</p>
        )}
      </Modal>
    </PageContainer>    
  );
};

export default routeTable;